<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import dayjs from "dayjs";
import { reTaskadd, regetTaskList } from '../../api/tasks/index';
import { ElMessage, ElNotification } from "element-plus";
import { changeGlobalNodesTarget } from 'element-plus/es/utils/index.mjs';
import { da } from 'element-plus/es/locale/index.mjs';
// 修改 TaskForm 接口
interface TaskForm {
  id:number
  title: string;
  content: string;
  taskTime: string;
  estimatedDuration: number;
  type: any;
  completed:0;
}

// 修改状态管理
let taskForm = ref<TaskForm>({
  id:-1,
  title: "",
  content: "",
  taskTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
  completed: false,
  estimatedDuration: 1,
  type: "学习",
});

const taskTypeOptions = [
  { label: "学习" },
  { label: "运动" },
  { label: "工作" },
  { label: "娱乐" },
  { label: "自定义" },
];

// 状态管理
const viewMode = ref<"calendar" | "list">("calendar"); // 视图模式
let tasks = ref<TaskForm[]>([]); // 所有任务
const newTaskContent = ref("");
const selectedDate = ref(dayjs().format("YYYY-MM-DD"));
let showDialog = ref(false);

// 计算属性
const groupedTasks = computed(() => {
  return tasks.value.reduce((acc: Record<string, TaskForm[]>, task) => {
    if (!acc[task.taskTime]) acc[task.taskTime] = [];
    acc[task.taskTime].push(task);
    return acc;
  }, {});
});

// 添加任务
// 修改添加任务方法
const addTask = async () => {
  try {
    await reTaskadd(taskForm.value);
    ElNotification({
      type: "success",
      message: "添加成功",
    });

    taskForm.value = {
      completed : false,
      id: 0,
      title: "",
      content: "",
      taskTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
      estimatedDuration: 1,
      type: "学习",
    };
    showDialog.value = false;
  } catch (error) {}
};

// 删除任务
const deleteTask = (taskId: number) => {
  tasks.value = tasks.value.filter((t) => t.id !== taskId);
};

// 切换任务状态
const toggleTaskStatus = (taskId: number) => {
  const task = tasks.value.find((t) => t.id === taskId);
  if (task) task.completed = !task.completed;
};

//获取事务列表
onMounted( async() => {
  const response:any = await regetTaskList();
  tasks = await response.data;
  console.log(tasks);
  
});

const change = (day:any) => {
  taskForm.value.taskTime = day;
  showDialog.value = true
}

// 检查某日期是否有任务
const hasTasksOnDate = (dateString: string) => {
  const date = dayjs(dateString).format('YYYY-MM-DD')
  return tasks.value.some(task => 
    dayjs(task.taskTime).format('YYYY-MM-DD') === date
  )
}

// 检查某日期是否有已完成任务
const hasCompletedTasksOnDate = (dateString: string) => {
  const date = dayjs(dateString).format('YYYY-MM-DD')
  return tasks.value.some(task => 
    dayjs(task.taskTime).format('YYYY-MM-DD') === date && 
    task.completed
  )
}

// 检查某日期是否有未完成任务
const hasUncompletedTasksOnDate = (dateString: string) => {
  const date = dayjs(dateString).format('YYYY-MM-DD')
  return tasks.value.some(task => 
    dayjs(task.taskTime).format('YYYY-MM-DD') === date && 
    !task.completed
  )
}

// 获取某日期的所有任务
const getTasksForDate = (dateString: string) => {
  const date = dayjs(dateString).format('YYYY-MM-DD')
  return tasks.value.filter(task => 
    dayjs(task.taskTime).format('YYYY-MM-DD') === date
  )
}

// 检查是否是选中的日期
const isDateSelected = (dateString: string) => {
  return selectedDate.value === dateString
}

// 处理日期点击
const handleDateClick = (dateString: string) => {
  showDialog.value = true
  selectedDate.value = dateString
  // 其他点击处理逻辑...
 
}
</script>

<template>
  <div class="task-manager">
    <!-- 模式切换 -->
    <div class="mode-switcher">
      <el-button
        :type="viewMode === 'calendar' ? 'primary' : ''"
        @click="viewMode = 'calendar'"
      >
        日历模式
      </el-button>
      <el-button
        :type="viewMode === 'list' ? 'primary' : ''"
        @click="viewMode = 'list';"
      >
        列表模式
      </el-button>
    </div>

    <!-- 日历模式 -->
    <el-calendar v-if="viewMode === 'calendar'" ref="calendarRef">
  <template #date-cell="{ data }">
    <div
      class="date-cell"
      :class="{
        'has-tasks': hasTasksOnDate(data.day),
        'has-completed': hasCompletedTasksOnDate(data.day),
        'has-uncompleted': hasUncompletedTasksOnDate(data.day),
        'selected': isDateSelected(data.day)
      }"
      @click="change(data.day)"
            
    >
      <div class="date-content">
        {{ dayjs(data.day).format("MM-DD") }}
        <div class="task-markers">
          <span
            v-for="task in getTasksForDate(data.day)"
            :key="task.id"
            class="task-marker"
            :class="{ completed: task.completed }"
            @click.stop="toggleTaskStatus(task.id)"
          >
            {{ task.completed ? "✓" : "•" }}
          </span>
        </div>
      </div>
    </div>
  </template>
</el-calendar>

    <!-- 列表模式 -->
    <div v-else class="list-view">
      <el-table :data="tasks" style="width: 100%">
        <el-table-column prop = "taskTime" label="计划日期" width="120">
        </el-table-column >
        <el-table-column prop="title" label="标题" />
        <el-table-column prop="estimatedDuration" label="花费时间（小时）" />
        <el-table-column prop="content" label="任务内容" />
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.completed ? 'success' : 'warning'" size="small">
              {{ row.completed ? "完成" : "待办" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-row :gutter="10">
              <el-col>
                <el-button size="small" @click="toggleTaskStatus(row.id)">
                  {{ row.completed ? "撤销" : " 完成" }}
                </el-button>
              </el-col>
              <el-col>
                <el-button
                  size="small"
                  type="danger"
                  @click="deleteTask(row.id)"
                >
                  删除
                </el-button>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <div class="add-task-btn">
        <el-button
          type="primary"
          @click="
            selectedDate = dayjs().format('YYYY-MM-DD');
            showDialog = true;
          "
        >
          添加新任务
        </el-button>
      </div>
    </div>

    <!-- 修改对话框部分 -->
    <el-dialog v-model="showDialog" title="添加新任务">
      <el-form :model="taskForm" label-width="120px">
        <el-form-item label="任务标题" required>
          <el-input v-model="taskForm.title" placeholder="请输入任务标题" />
        </el-form-item>

        <el-form-item label="任务类型" required>
          <el-select
            v-model="taskForm.type"
            placeholder="请选择任务类型"
            style="width: 100%"
          >
            <el-option
              v-for="option in taskTypeOptions"
              :key="option.label"
              :label="option.label"
              :value="option.label"
            />
          </el-select>

          <el-input
            v-if="!['学习', '工作', '娱乐', '运动'].includes(taskForm.type)"
            v-model="taskForm.type"
            placeholder="请输入自定义类型"
            style="margin-top: 10px"
          />
        </el-form-item>

        <el-form-item label="任务内容" required>
          <el-input
            v-model="taskForm.content"
            type="textarea"
            :rows="3"
            placeholder="请输入任务详细内容"
          />
        </el-form-item>

        <el-form-item label="任务时间" required>
          <el-date-picker
            v-model="taskForm.taskTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="预计时长" required>
          <el-input-number
            v-model="taskForm.estimatedDuration"
            :min="0.5"
            :max="24"
            :step="0.5"
            controls-position="right"
          />
          <span class="duration-unit">小时</span>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="addTask"
          >确认添加</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.task-manager {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;

  .mode-switcher {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
  }

  .date-cell {
    height: 100%;
    padding: 8px;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      background-color: #f5f7fa;
    }

    .task-markers {
      display: flex;
      gap: 2px;
      flex-wrap: wrap;
      margin-top: 4px;
    }

    .task-marker {
      font-size: 12px;
      color: #e6a23c;

      &.completed {
        color: #67c23a;
      }
    }
  }

  .list-view {
    .add-task-btn {
      margin-top: 20px;
      text-align: right;
    }
  }

  .task-input {
    margin-top: 15px;
  }
}

.duration-unit {
  margin-left: 10px;
  color: #666;
}

.date-cell {
  height: 100%;
  padding: 8px;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    background-color: #f5f7fa;
  }
  
  &.has-tasks {
    background-color: #f0f9eb;
    border-left: 3px solid #67c23a;
  }
  
  &.has-completed {
    background-color: #f0f9eb;
  }
  
  &.has-uncompleted {
    background-color: #fdf6ec;
    border-left: 3px solid #e6a23c;
  }
  
  &.selected {
    background-color: #ecf5ff;
    border: 1px solid #409eff;
  }
}

.task-markers {
  display: flex;
  flex-wrap: wrap;
  gap: 2px;
  margin-top: 4px;
}

.task-marker {
  display: inline-block;
  width: 16px;
  height: 16px;
  line-height: 16px;
  text-align: center;
  font-size: 12px;
  border-radius: 50%;
  
  &.completed {
    color: #67c23a;
    background-color: #f0f9eb;
  }
  
  &:not(.completed) {
    color: #e6a23c;
    background-color: #fdf6ec;
  }
}
</style>
